package com.roobo.demo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.roobo.mqttsdk.manager.DeviceInfoManager;
import com.roobo.mqttsdk.manager.ResultInterface;

import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

/**
 * 设备信息上报时机：
 * 1）开机连接上wifi之后或者wifi重新连接上之后全量上报设备基本信息
 * 2）设备信息改变之后同步对应的改变信息，无需全量同步，只需要同步改变项。不建议定时同步，建议在设备状态改变后上报变化后的状态
 */


public class ReportDeviceInfoActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = ReportDeviceInfoActivity.class.getSimpleName();

    private Button mReportAllBtn;
    private Button mReportSDCardAvailableBtn;
    private Button mReportSDCardTotalBtn;
    private Button mReportElectricityBtn;

    private Button mReportVolumeBtn;
    private Button mReportMacBtn;
    private Button mReportIPAddressBtn;

    private Button mReportPowerStateBtn;
    private Button mReportFirmwareVersionBtn;
    private Button mReportEarLightStateBtn;

    private Button mReportChildClockStateBtn;
    private Button mReportDeviceCustomInfoBtn;

    private AudioManager mAudioManager;

    private int mBatteryLevel;

    private int mBatteryState;

    private BroadcastReceiver mBatterReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //设备电量
            mBatteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            //充电状态
            int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
            if (state == BatteryManager.BATTERY_STATUS_CHARGING) {
                mBatteryState = DeviceInfoManager.POWER_STATE_CHARGING;
            } else {
                mBatteryState = DeviceInfoManager.POWER_STATE_UN_CHARGE;
            }
            Log.d(TAG, "mBatteryLevel:" + mBatteryLevel + " mBatteryState:" + mBatteryState);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_device_info);
        setTitle(getResources().getString(R.string.report_device_info_activity_title));
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        initViews();
        registerBatteryStateReceiver();
    }

    private void initViews() {
        mReportAllBtn = findViewById(R.id.report_all_btn);
        mReportSDCardAvailableBtn = findViewById(R.id.report_sdcard_available_btn);
        mReportSDCardTotalBtn = findViewById(R.id.report_sdcard_total_btn);

        mReportElectricityBtn = findViewById(R.id.report_electricity_btn);
        mReportVolumeBtn = findViewById(R.id.report_volume_btn);
        mReportMacBtn = findViewById(R.id.report_mac_btn);

        mReportIPAddressBtn = findViewById(R.id.report_ip_address_btn);
        mReportPowerStateBtn = findViewById(R.id.report_power_state_btn);
        mReportFirmwareVersionBtn = findViewById(R.id.report_firmware_version_btn);

        mReportEarLightStateBtn = findViewById(R.id.report_ear_light_state_btn);
        mReportChildClockStateBtn = findViewById(R.id.report_child_clock_state_btn);
        mReportDeviceCustomInfoBtn = findViewById(R.id.report_device_custom_info_btn);

        mReportAllBtn.setOnClickListener(this);
        mReportSDCardAvailableBtn.setOnClickListener(this);
        mReportSDCardTotalBtn.setOnClickListener(this);

        mReportElectricityBtn.setOnClickListener(this);
        mReportVolumeBtn.setOnClickListener(this);
        mReportMacBtn.setOnClickListener(this);

        mReportIPAddressBtn.setOnClickListener(this);
        mReportPowerStateBtn.setOnClickListener(this);
        mReportFirmwareVersionBtn.setOnClickListener(this);

        mReportEarLightStateBtn.setOnClickListener(this);
        mReportChildClockStateBtn.setOnClickListener(this);
        mReportDeviceCustomInfoBtn.setOnClickListener(this);
    }

    private void registerBatteryStateReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(mBatterReceiver, intentFilter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.report_all_btn:
                sendAllDeviceInf();
                break;
            case R.id.report_sdcard_available_btn:
                setSDCardAvailable();
                sendDeviceInfo();
                break;
            case R.id.report_sdcard_total_btn:
                setSDCardTotal();
                sendDeviceInfo();
                break;
            case R.id.report_electricity_btn:
                setElectricity();
                sendDeviceInfo();
                break;
            case R.id.report_volume_btn:
                setVolume();
                sendDeviceInfo();
                break;
            case R.id.report_mac_btn:
                setMac();
                sendDeviceInfo();
                break;
            case R.id.report_ip_address_btn:
                setIPAddress();
                sendDeviceInfo();
                break;
            case R.id.report_power_state_btn:
                setPowerState();
                sendDeviceInfo();
                break;
            case R.id.report_firmware_version_btn:
                setFirmwareVersion();
                sendDeviceInfo();
                break;
            case R.id.report_ear_light_state_btn:
                setEarLightState();
                sendDeviceInfo();
                break;
            case R.id.report_child_clock_state_btn:
                setChildLockState();
                sendDeviceInfo();
                break;
            case R.id.report_device_custom_info_btn:
                setDeviceCustomInfo();
                sendDeviceInfo();
                break;
        }
    }

    private void setSDCardAvailable() {
        long fSpace = Environment.getExternalStorageDirectory().getFreeSpace();
        int freeSpace = (int) (fSpace / 1024 / 1024);//以MB为单位
        Log.d(TAG, "setSDCardAvailable freeSpace:" + freeSpace);
        DeviceInfoManager.getInstance().setSDCardAvailable(freeSpace);
    }

    private void setSDCardTotal() {
        long tSpace = Environment.getExternalStorageDirectory().getTotalSpace();
        int totalSpace = (int) (tSpace / 1024 / 1024);//以MB为单位
        Log.d(TAG, "totalSpace total:" + totalSpace);
        DeviceInfoManager.getInstance().setSDCardTotal(totalSpace);
    }

    private void setElectricity() {
        Log.d(TAG, "setElectricity mBatteryLevel:" + mBatteryLevel);
        //电量百分比
        DeviceInfoManager.getInstance().settElectricity(mBatteryLevel);
    }

    private void setMac() {
        String mac = getNewMac();
        Log.d(TAG, "setMac mac:" + mac);
        DeviceInfoManager.getInstance().setMac(mac);
    }

    private static String getNewMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    private void setIPAddress() {
        //获取wifi服务
        WifiManager wifi = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifi.isWifiEnabled()) {
            wifi.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifi.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        String ipAddress = intToIp(ip);
        Log.d(TAG, "setIPAddress ipAddress:" + ipAddress);
        DeviceInfoManager.getInstance().setIPAddress(ipAddress);
    }

    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    private void setPowerState() {
        Log.d(TAG, "setPowerState mBatteryState:" + mBatteryState);
        //电源状态，POWER_STATE_UN_CHARGE未接通充电，POWER_STATE_UN_CHARGE为充电中
        DeviceInfoManager.getInstance().setPowerState(mBatteryState);
    }

    private void setFirmwareVersion() {
        String firmwareVersion = "Android " + android.os.Build.VERSION.RELEASE;//以安卓系统版本为例
        Log.d(TAG, "setFirmwareVersion firmwareVersion:" + firmwareVersion);
        DeviceInfoManager.getInstance().setFirmwareVersion(firmwareVersion);

    }

    private void setEarLightState() {
        Log.d(TAG, "setEarLightState state:" + DeviceInfoManager.EAR_LIGHT_TURN_ON);
        //耳灯状态，EAR_LIGHT_TURN_OFF关闭，EAR_LIGHT_TURN_ON开启
        DeviceInfoManager.getInstance().setEarLightState(DeviceInfoManager.EAR_LIGHT_TURN_ON);
    }

    private void setChildLockState() {
        Log.d(TAG, "setChildLockState state:" + DeviceInfoManager.CHILD_CLOCK_TURN_OFF);
        //童锁状态，CHILD_CLOCK_TURN_OFF关闭，EAR_LIGHT_TURN_ON开启
        DeviceInfoManager.getInstance().setChildLockState(DeviceInfoManager.CHILD_CLOCK_TURN_OFF);
    }

    private void setDeviceCustomInfo() {
        String key = "key1";//自定义
        String value = "1";//自定义
        Log.d(TAG, "setDeviceCustomInfo key:" + key + " value:" + value + " type:" + DeviceInfoManager.INFO_TYPE_DIGIT);
        //特有信息类型，INFO_TYPE_CHARACTER value字符串，INFO_TYPE_DIGIT value数字
        DeviceInfoManager.getInstance().setDeviceCustomInfo(key, value, DeviceInfoManager.INFO_TYPE_DIGIT);
    }


    /***
     * 系统音量 = (int)(系统最大音量 * value/100)。
     */
    private void setVolume() {
        Log.d(TAG, "setVolume");
        int percentage = 30;//设置30%的音量
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        Log.d(TAG, "setVolume max:" + max);
        int value = max * percentage / 100;
        Log.d(TAG, "setVolume value:" + value);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value, AudioManager.FLAG_PLAY_SOUND);//调整音乐声
        DeviceInfoManager.getInstance().setVolume(percentage);
    }

    private void toastResult(int resultCode) {
        if (resultCode == DeviceInfoManager.CODE_REPORT_SUCCESS) {
            Toast.makeText(ReportDeviceInfoActivity.this.getApplicationContext(), ReportDeviceInfoActivity.this.getApplicationContext().getResources().getString(R.string.report_success),
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(ReportDeviceInfoActivity.this.getApplicationContext(), ReportDeviceInfoActivity.this.getApplicationContext().getResources().getString(R.string.report_fail),
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void sendDeviceInfo() {
        DeviceInfoManager.getInstance().sendDeviceInfo(new ResultInterface() {
            @Override
            public void onResult(int code, String message) {
                Log.d(TAG, "code:" + code + " message:" + message);
                toastResult(code);
            }
        });
    }

    private void sendAllDeviceInf() {
        setSDCardTotal();
        setSDCardAvailable();
        setVolume();
        setChildLockState();
        setDeviceCustomInfo();
        setEarLightState();
        setFirmwareVersion();
        setMac();
        setIPAddress();
        setPowerState();
        setElectricity();
        sendDeviceInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBatterReceiver);
    }
}
